﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;
using System.Security.Cryptography;
using System.Text;
public partial class Account_ChangePassword : System.Web.UI.Page
{
    DBAcess db = new DBAcess();
    protected void Page_Load(object sender, EventArgs e)
    {
        Page.Title = "Change Password | Nexus-Z Auto Rental";
        if (Session["employeeID"] == null)
        {
            Response.Redirect("../Default.aspx");
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        MySqlCommand cmd = new MySqlCommand("select password from employees where employee_id=@employeeID;", db.returnCon());
        cmd.Parameters.AddWithValue("@employeeID", Session["employeeID"]);
        db.open();
        MySqlDataReader dr = cmd.ExecuteReader();
       
        while (dr.Read())
        {
            if (getMd5Hash(TextBox1.Text).Equals(dr.GetValue(0)))
            {
                db.close();
                db.open();
                cmd = new MySqlCommand("update employees set password=@password where employee_id=@employeeID;", db.returnCon());
                cmd.Parameters.AddWithValue("@password", getMd5Hash(TextBox3.Text));
                cmd.Parameters.AddWithValue("@employeeID", Session["employeeID"]);
                cmd.ExecuteNonQuery();
                db.close();
                Response.Redirect("~/Account/ChangePasswordSuccess.aspx");
            }
            else
            {
                Label1.Text = "incorrect password";
            }
        }


        
    }
    static string getMd5Hash(string input)
    {
        MD5 md5Hasher = MD5.Create();

        byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));

        StringBuilder sBuilder = new StringBuilder();
        for (int i = 0; i < data.Length; i++)
        {
            sBuilder.Append(data[i].ToString("x2"));
        }
        return sBuilder.ToString();
    }
}